<template>
  <div>
    <el-dialog
      :title="title"
      center
      :visible="open"
      :modal="open"
      @close="close()"
      :close-on-click-modal="false"
      width="600px"
    >
      <el-form ref="editForm" :model="editForm" :rules="rules" label-width="100px">
        <el-form-item label="上级组织" prop="treeDeptIds">
          <ht-dept-select-tree
            ref="deptTree"
            v-model="treeDeptIds"
            :radio="true"
            node-key="code"
            :disabled="disabled"
            :tenantSelect="false"
            :tempNodeType="isTenant ? 'tenant' : 'dept'"
            @otherChangeChecked="treeChangeChecked"
          ></ht-dept-select-tree>
<!--                    <span>{{editForm.parentName}}</span>-->
          <!--          <el-input v-model="editForm.parentName" v-if="disabled" disabled />-->
        </el-form-item>
        <el-form-item label="组织编号" prop="deptCode">
          <el-input
            v-model.trim="editForm.deptCode"
            placeholder="请输入组织编号"
            :disabled="disabled"
            oninput="value=value.replace(',','')"
          />
        </el-form-item>
        <el-form-item label="组织名称" prop="deptName">
          <el-input v-model="editForm.deptName" placeholder="请输入组织名称" />
        </el-form-item>
        <el-form-item label="显示排序" prop="orderNum">
          <el-input
            v-model.number="editForm.orderNum"
            placeholder="请输入显示排序"
            oninput="value=value.replace(/[^0-9]/g,'')"
            maxlength="5"
          />
        </el-form-item>
        <el-form-item label="负责人" prop="leader">
          <el-input v-model="editForm.leader" placeholder="请输入负责人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="联行行号" prop="bankNo">
          <BrnoInput v-model="editForm.bankNo" placeholder="请输入联行行号" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="editForm.status">
            <el-radio v-for="(item, index) in dictMap.sys_normal_disable" :key="index" :label="Number(item.value)">
              {{ item.text }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <ht-extend-form
          ref="htExtendForm"
          v-if="extendParams"
          :extendParams="extendParams"
          :expandValueInfoMap="editForm.expandValueInfoMap"
          :dictReqFun="getDictReq"
          labelWidth = "100px"
        />
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addOrUpdate">确 定</el-button>
        <el-button @click="close">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  checkDeptCode,
  checkDeptName,
  selectDeptNameById,
  findDeptInfoById,
  updateDeptInfo,
  addDeptInfo,
} from "@/api/authority_app/deptInfo/deptInfo";
import { dialogMixin } from "@/libs/dialogMixin";
import BrnoInput from "@/views/components/BrnoInput/index.vue";

export default {
  name: "AddUpdate",
  components: {BrnoInput},
  mixins: [dialogMixin],
  data() {
    // 表单校验
    var checkDeptNameUnique = (rule, value, callback) => {
      if (!value) {
        callback(new Error("组织名称不能为空"));
      } else {
        delete this.editForm.createTime;
        delete this.editForm.updateTime;
        this.$nextTick(() => {
          checkDeptName(this.editForm).then((response) => {
            var result = response.result;
            if (!result) {
              callback(new Error("组织名称已经存在"));
            } else {
              callback();
            }
          });
        });
      }
    };
    var checkDeptCodeUnique = (rule, value, callback) => {
      if (!value) {
        callback(new Error("组织编码不能为空"));
      } else {
        delete this.editForm.createTime;
        delete this.editForm.updateTime;
        this.$nextTick(() => {
          checkDeptCode(this.editForm).then((response) => {
            var result = response.result;
            if (!result) {
              callback(new Error("组织编码已经存在"));
            } else {
              callback();
            }
          });
        });
      }
    };
    var checkNum = (rule, value, callback) => {
      if (!value) {
        callback(new Error("排序不能为空"));
      }
      if (!Number(value)) {
        callback(new Error("只能输入数字"));
      }
      if (String(value).length > 5) {
        callback(new Error("长度为1-5位"));
      }
      callback();
    };

    return {
      open: false,
      title: "",
      disabled: false,
      parentId: "",
      parentCode: "",
      // 租户机构树数据
      deptTreeOptions: [],
      treeDeptIds: "",
      parentName: "",
      checkedDeptIds: "",
      isTenant: false,
      rules: {
        treeDeptIds: [
          {
            required: true,
            message: "请选择上级组织",
            trigger: "change",
            validator: (rule, value, callback) => {
              this.$nextTick(() => {
                if (!this.treeDeptIds) {
                  callback(new Error("请选择上级组织"));
                } else {
                  callback();
                }
              });
            },
          },
        ],
        leader: [
          { min: 1, max: 64, message: "长度为1-64位", trigger: "blur" },
        ],
        bankNo: [
          { min: 1, max: 16, message: "长度为1-16位", trigger: "blur" },
        ],
        deptCode: [
          { required: true, trigger: "blur", validator: checkDeptCodeUnique },
          { min: 1, max: 50, message: "长度为1-50位", trigger: "blur" },
        ],
        deptName: [
          { required: true, trigger: "blur", validator: checkDeptNameUnique },
          { min: 1, max: 64, message: "长度为1-64位", trigger: "blur" },
        ],
        orderNum: [{ required: true, validator: checkNum, trigger: "blur" }],
        phone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号",
            trigger: "blur",
          },
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱格式",
            trigger: ["blur", "change"],
          },
        ],
      },
    };
  },
  props: {
    extendParams: {
      type: Array,
      default: {},
    },
  },
  created() {
    this.loadDicts(["sys_normal_disable"]);
  },
  methods: {
    show(id = "", disabled = false, parentCode = "", parentTenantCode = "", isTenant = false) {
      this.isTenant = isTenant;
      // this.$set(this,'editForm',{})parentCode
      this.$set(this, "editForm", {
        tenantCode: parentTenantCode,
      });
      this.resetForm("editForm");
      this.disabled = disabled;
      this.parentCode = parentCode;
      this.treeDeptIds = parentCode ? parentCode : "";
      if (id) {
        findDeptInfoById(id).then((res) => {
          this.$set(this, "editForm", res.result);
          this.treeDeptIds = res.result.parentCode;
          this.checkedDeptIds = res.result.parentId;
          // this.isTenant = res.result.parentId == '0';
          this.$nextTick(() => {
            this.$refs.htExtendForm.genData();
          });
        });

        this.title = "编辑机构";
      } else {
        this.title = "新增机构";
        this.$nextTick((res) => {
          this.$refs.htExtendForm.genData();
        });
      }
      this.open = true;

      this.$nextTick(() => {
        if (this.$refs.deptTree) this.$refs.deptTree.reloadTreeData();
      });
    },
    getDictReq(dictCode) {
      return this.getDicts(dictCode);
    },
    treeChangeChecked(res) {
      console.log("treeChangeChecked", res);
      this.checkedDeptIds = res.map((x) => x.id).join(",");
    },
    //新增\编辑提交接口
    addOrUpdate() {
      this.treeChangeChecked(this.$refs.deptTree.getSelectDataList());
      this.editForm.parentId = this.checkedDeptIds;
      this.editForm.expandValueInfoMap = this.$refs.htExtendForm.getExtendParamsValue();

      delete this.editForm.createTime;
      delete this.editForm.updateTime;
      this.$refs["editForm"].validate((valid) => {
        if (valid) {
          if (this.editForm.id) {
            // this.editForm.parentId = this.treeDeptIds;
            updateDeptInfo(this.editForm).then((response) => {
              this.msgSuccess("修改成功");
              this.close(true);
            });
          } else {
            addDeptInfo(this.editForm).then((response) => {
              this.msgSuccess("新增成功");
              this.close(true);
            });
          }
        }
      });
    },
    //取消接口
    close(state = false) {
      this.treeDeptIds = "";
      this.$emit("editComplete", state);
      this.open = false;
    },
  },
};
</script>
